const jwt = require('jsonwebtoken')

const ACCESS_TOKEN_SECRET = process.env.ACCESS_TOKEN_SECRET || 'dev_access_secret'

function verifyAccessToken(req, res, next) {
  try {
    const auth = req.headers['authorization'] || ''
    const token = auth.startsWith('Bearer ') ? auth.slice(7) : null
    if (!token) return res.status(401).json({ message: '未提供访问令牌' })
    const payload = jwt.verify(token, ACCESS_TOKEN_SECRET)
    req.user = { user_id: payload.user_id, username: payload.username }
    next()
  } catch (err) {
    return res.status(401).json({ message: '访问令牌无效或已过期' })
  }
}

module.exports = { verifyAccessToken }